package com.gopay.bis.web.controller.scan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.gopay.bis.domain.order.OrderInfo;
import com.gopay.common.Result;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.spdb.agpay.PayNotify;
import com.gopay.common.util.FastJsonUtil;

@Controller
@Scope("prototype")
public class SdkPaySpdbServerRes extends ScanPayBankResBase {
	
	/**
	 * 定义日志对象
	 */
	private static Log logger = LogFactory.getLog(SdkPaySpdbServerRes.class);
	
	@RequestMapping(value = "/aPaySpdbServerRes")
	protected void execute(HttpServletRequest request, HttpServletResponse response) {
		logger.error("---------------aPaySpdbServerRes  bankback ---------------");
		super.execute(request, response);

	}

	@Override
	protected BaseMessage buildMessage(HttpServletRequest request) {
		// TODO Auto-generated method stub
		//String jsonStr=parseRequst(request);
		String jsonStr=parseRequstParam(request);	
		PayNotify body = (PayNotify) toBean(jsonStr,PayNotify.class);
		body.setFront(false);
//		body.setBankBusProd(BisBankBusinessProd._17);
//		body.setBank(BankConstants.BANK_LOGO_WECHAT);
		body.setBankOrderId(body.getOrderNum());
		body.setPlainMessage(body.getSign());
		if(StringUtils.isNotBlank(body.getTxamt())){
			body.setAmount(new BigDecimal(body.getTxamt()).divide(new BigDecimal(100)));
		}
		return body;
	}

	@Override
	protected OrderInfo buildOrderInfo(HttpServletRequest request, Result result) {
		// TODO Auto-generated method stub
		PayNotify message = (PayNotify)result.getModel("res");
		logger.error("SdkPaySpdbServerRes:" + ToStringBuilder.reflectionToString(message));
		OrderInfo orderInfo = new OrderInfo();
		if (message != null) {
			if ("成功".equals(message.getErrorDetail())) {
				orderInfo.setOrderId(message.getOrderId());
				orderInfo.setAmt(message.getAmount().toString());
				orderInfo.setNotifyNum("1");
				orderInfo.setPayStatus("00");
				orderInfo.setRetCode("00");
				orderInfo.setRetMsg("");
				orderInfo.setIsNotify(true);
			} else {
				orderInfo.setOrderId(message.getOrderId());
				orderInfo.setAmt(message.getAmount().toString());
				orderInfo.setNotifyNum("1");
				orderInfo.setPayStatus("01");
				orderInfo.setRetCode("01");
				orderInfo.setRetMsg("");
			}
		}
		return orderInfo;
	}

	@Override
	protected boolean checkParameters(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected boolean notifyBank(HttpServletResponse response,
			OrderInfo orderInfo) {
		// TODO Auto-generated method stub
		try {
            response.setContentType("text/html;charset=utf-8");
            String notifyMsg="SUCCESS";
            logger.info("notifyBank WECHAT send content: \n["+notifyMsg +"]");
            response.setContentLength(notifyMsg.getBytes().length);
            response.getOutputStream().write(notifyMsg.getBytes());
            response.getOutputStream().close();
            return true;
        } catch (IOException e) {
        	logger.info(e.getMessage());
        }
        return true;
	}
	
	private String parseRequst(HttpServletRequest request) {
		BufferedReader reader = null;  
        StringBuilder sb = new StringBuilder();  
        try{  
            reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));  
            String line = null;  
            while ((line = reader.readLine()) != null){  
                sb.append(line);  
            }  
        } catch (IOException e){  
            e.printStackTrace();  
        } finally {  
            try{  
                if (null != reader){ reader.close();}  
            } catch (IOException e){  
                e.printStackTrace();  
            }  
        }  
        logger.info("parse return jsonStr :"+sb.toString());
        return sb.toString();  
	}
	private String parseRequstParam(HttpServletRequest request) {
		Map<String, String> params = new TreeMap<String, String>();
		parseRequst(request);
		// 取出所有参数是为了验证签名
		Enumeration<String> parameterNames = request.getParameterNames();
		String parameterName=null;
		String jsonStr=null;
		while (parameterNames.hasMoreElements()) {
			parameterName = parameterNames.nextElement();		
		}
		if(StringUtils.isNotBlank(parameterName)){		
			String parBefore=parameterName.replace("[", "");
			String parAfter=parBefore.replace("]", "");			 
			String[] strPra=parAfter.split("&");
			Map paramMap=new HashMap<>();
			for(int i=0;i<strPra.length;i++){
				String[] childPram=strPra[i].split("=");
				paramMap.put(childPram[0], childPram[1]);
			}
			jsonStr =FastJsonUtil.collectToString(paramMap);
		}
		logger.info("parse return jsonStr :"+jsonStr);
		return jsonStr;
	}
	private <T> T toBean(String json, Class<T> clazz) {
		T t = JSON.parseObject(json,clazz);
		return t;
	}
	public static void main(String[]args){

		
	}
}
